﻿/* **
 * WebQ - a Web Questionare / Survey Framework
 * Andrew Adhi Ariane Murniadi / 2009
 * GPL
 * $Id$
 *									** */

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebQ.Core {
	/// <summary>
	/// Postback data handler and processing. This class gets the raw postbacked data and process
	/// the identifier (normalize it) for use by framework entities. 
	/// </summary>
	/// <remarks>ASP.Net added hierarcical id naming scheme to ensure uniqueness of the id in a form.
	/// While this is good for the overall framework, this name mangling scheme added a layer of
	/// unpredictability especially for dynamic controls where you dont always produce the same
	/// component after each postback. This class actually tries to normalize the mangled id that 
	/// ASP.Net assigned to the controls to ids that is predictable by the framework entities.</remarks>
	public class WebQPostbackExtractor {
		private String m_postbackPrefix;
		private NameValueCollection m_postbackData;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="prefix">Base control Client Id including the IdSeparator</param>
		/// <param name="postbackedData">Collection of postbacked data</param>
		public WebQPostbackExtractor ( String prefix, NameValueCollection postbackedData ) {
			m_postbackPrefix = prefix;
			m_postbackData = postbackedData;
		}

		/// <summary>
		/// Extract and normalized id of postbacked data
		/// </summary>
		/// <returns>Extracted and Normalized postbacked data collection</returns>
		public Dictionary<String, String> ExtractPostbackData () {
			Dictionary<String, String> ret = new Dictionary<String, String> ();

			foreach ( String key in m_postbackData.AllKeys ) {
				if ( key.StartsWith ( m_postbackPrefix ) ) {
					String val = m_postbackData[key];
					String newKey = key.Substring ( m_postbackPrefix.Length );
					ret.Add ( newKey, val );
				}
			}

			return ret;
		}

	}
}
